<template>
  <view class="page-container">
    <scroll-view scroll-y class="form-scroll">
      <!-- 场地图片轮播 -->
      <view class="image-section" v-if="!isEditing && venueData.id">
        <swiper class="venue-swiper" indicator-dots circular>
          <swiper-item v-for="(image, index) in venueImages" :key="index">
            <image :src="image" mode="aspectFill" class="swiper-image"></image>
          </swiper-item>
        </swiper>
        <view class="image-overlay">
          <view class="back-btn" @click="goBack">
            <uni-icons type="back" size="20" color="#fff"></uni-icons>
          </view>
          <view class="edit-btn" @click="toggleEdit">
            <uni-icons type="compose" size="20" color="#fff"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 场地状态卡片 -->
      <view class="status-section" v-if="!isEditing && venueData.id">
        <view class="status-card">
          <view class="status-info">
            <text class="status-label">当前状态</text>
            <uni-tag 
              :text="getStatusText(venueData.status)" 
              :type="getStatusType(venueData.status)" 
              size="normal"
            />
          </view>
          <view class="status-actions">
            <button class="status-btn" @click="showStatusModal">切换状态</button>
            <button 
              class="book-btn" 
              @click="handleQuickBook"
              :disabled="venueData.status !== 1"
            >
              {{ venueData.status === 1 ? '立即预订' : '不可预订' }}
            </button>
          </view>
        </view>
      </view>

      <!-- 表单内容 -->
      <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-width="80px" label-align="right">
        <uni-card title="基本信息" :is-shadow="true">
          <uni-forms-item label="场地名称" name="name" required>
            <uni-easyinput 
              v-model="formData.name" 
              placeholder="请输入场地名称" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="场地类型" name="venue_type" required>
            <uni-data-select 
              v-model="formData.venue_type" 
              :localdata="venueTypeOptions" 
              placeholder="请选择场地类型"
              :disabled="!isEditing"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="容纳人数" name="capacity" required>
            <uni-number-box 
              v-model="formData.capacity" 
              :min="1" 
              :max="1000"
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="场地面积" name="area" required>
            <view class="input-with-unit">
              <uni-easyinput 
                v-model="formData.area" 
                type="number"
                placeholder="请输入面积" 
                :disabled="!isEditing"
              />
              <text class="unit">㎡</text>
            </view>
          </uni-forms-item>
          <uni-forms-item label="排序" name="sort_order">
            <uni-number-box 
              v-model="formData.sort_order" 
              :min="0" 
              :max="999"
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="价格设置" :is-shadow="true">
          <uni-forms-item label="小时价格" name="hour_price" required>
            <view class="input-with-unit">
              <uni-easyinput 
                v-model="formData.hour_price" 
                type="digit"
                placeholder="请输入小时价格" 
                :disabled="!isEditing"
              />
              <text class="unit">元/时</text>
            </view>
          </uni-forms-item>
          <uni-forms-item label="全天价格" name="day_price" required>
            <view class="input-with-unit">
              <uni-easyinput 
                v-model="formData.day_price" 
                type="digit"
                placeholder="请输入全天价格" 
                :disabled="!isEditing"
              />
              <text class="unit">元/天</text>
            </view>
          </uni-forms-item>
          <uni-forms-item label="分时段定价" name="time_based_pricing" v-if="isEditing">
            <time-based-pricing-editor 
              v-model="formData.time_based_pricing"
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="场地设施" :is-shadow="true" v-if="isEditing || facilitiesList.length > 0">
          <uni-forms-item label="设施配置" name="facilities">
            <facility-editor 
              v-model="facilitiesList" 
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="场地图片" :is-shadow="true" v-if="isEditing">
          <uni-forms-item label="场地图片" name="images">
            <uni-file-picker
              v-model="imageFiles"
              file-mediatype="image"
              mode="grid"
              :limit="5"
              @select="handleImageUpload"
              @delete="handleImageDelete"
              :auto-upload="false"
            />
          </uni-forms-item>
        </uni-card>

        <uni-card title="其他信息" :is-shadow="true" v-if="isEditing || formData.description || formData.opening_hours">
          <uni-forms-item label="开放时间" name="opening_hours">
            <uni-easyinput 
              v-model="formData.opening_hours" 
              type="textarea"
              placeholder="请输入开放时间说明"
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="特殊提示" name="special_notice">
            <uni-easyinput 
              v-model="formData.special_notice" 
              placeholder="请输入特殊提示"
              :disabled="!isEditing"
            />
          </uni-forms-item>
          <uni-forms-item label="场地描述" name="description">
            <uni-easyinput 
              v-model="formData.description" 
              type="textarea" 
              placeholder="请输入场地描述"
              :disabled="!isEditing"
            />
          </uni-forms-item>
        </uni-card>
      </uni-forms>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions safe-area-inset-bottom">
      <button v-if="!isEditing && venueData.id" class="edit-btn-footer" @click="toggleEdit">
        编辑场地
      </button>
      <template v-else>
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button class="submit-btn" @click="handleSubmit">{{ venueData.id ? '保存' : '创建' }}</button>
      </template>
    </view>

    <!-- 状态切换弹窗 -->
    <uni-popup ref="statusPopup" type="bottom">
      <view class="status-modal">
        <view class="modal-header">
          <text class="modal-title">切换场地状态</text>
          <uni-icons type="close" size="20" @click="closeStatusModal"></uni-icons>
        </view>
        <view class="status-options">
          <view 
            v-for="status in statusOptions" 
            :key="status.value"
            class="status-option"
            @click="changeVenueStatus(status.value)"
          >
            <uni-tag :text="status.text" :type="status.type" size="small" />
            <text class="status-desc">{{ status.desc }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchVenueDetail, createVenue, updateVenue, fetchVenueTypes } from '@/api/store';
import type { Venue, VenueType } from '@/types/store';
import FacilityEditor from '../stores/components/FacilityEditor.vue';
import TimeBasedPricingEditor from './components/TimeBasedPricingEditor.vue';

const formRef = ref<any>(null);
const statusPopup = ref<any>(null);
const isEditing = ref(false);
const venueData = ref<Partial<Venue>>({});

const formData = reactive<Partial<Venue>>({
  name: '',
  store_id: undefined,
  venue_type: '',
  capacity: 1,
  area: 0,
  hour_price: 0,
  day_price: 0,
  time_based_pricing: '',
  description: '',
  facilities: '',
  images: '',
  status: 1,
  sort_order: 0,
  opening_hours: '',
  special_notice: '',
});

const rules = {
  name: { rules: [{ required: true, errorMessage: '请输入场地名称' }] },
  venue_type: { rules: [{ required: true, errorMessage: '请选择场地类型' }] },
  capacity: { rules: [{ required: true, errorMessage: '请输入容纳人数' }] },
  area: { rules: [{ required: true, errorMessage: '请输入场地面积' }] },
  hour_price: { rules: [{ required: true, errorMessage: '请输入小时价格' }] },
  day_price: { rules: [{ required: true, errorMessage: '请输入全天价格' }] },
};

const venueTypeOptions = ref<{ value: string; text: string }[]>([]);
const imageFiles = ref<any[]>([]);
const facilitiesList = ref<string[]>([]);

const pageTitle = ref('新增场地');
const venueId = ref<number | null>(null);
const storeId = ref<number | null>(null);

// 状态选项
const statusOptions = [
  { value: 1, text: '空闲中', type: 'success', desc: '场地可正常使用' },
  { value: 2, text: '使用中', type: 'primary', desc: '场地正在被使用' },
  { value: 3, text: '保洁中', type: 'warning', desc: '场地正在保洁' },
  { value: 4, text: '待保洁', type: 'default', desc: '场地需要保洁' },
  { value: 5, text: '维护中', type: 'error', desc: '场地正在维护' },
];

// 计算场地图片列表
const venueImages = computed(() => {
  if (venueData.value.images) {
    try {
      const images = JSON.parse(venueData.value.images);
      return Array.isArray(images) ? images : [images];
    } catch (error) {
      return [venueData.value.images];
    }
  }
  return ['/static/images/venue-placeholder.png'];
});

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.text : '未知';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const option = statusOptions.find(opt => opt.value === status);
  return option ? option.type : 'default';
};

// 文件上传
const uploadFile = (file: any): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: '/api/v1/upload',
      filePath: file.tempFilePath,
      name: 'file',
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data);
        if (data.success) {
          resolve(data.data);
        } else {
          reject(new Error(data.message || '上传失败'));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const handleImageUpload = async (e: any) => {
  try {
    const urls = await Promise.all(e.tempFiles.map((file: any) => uploadFile(file)));
    const newImages = urls.map(url => ({ url }));
    imageFiles.value.push(...newImages);
    const allUrls = imageFiles.value.map(f => f.url);
    formData.images = JSON.stringify(allUrls);
  } catch (error: any) {
    uni.showToast({ title: error.message || '图片上传失败', icon: 'none' });
  }
};

const handleImageDelete = (e: any) => {
  const deletedUrl = e.tempFilePath;
  imageFiles.value = imageFiles.value.filter(f => f.url !== deletedUrl);
  const allUrls = imageFiles.value.map(f => f.url);
  formData.images = JSON.stringify(allUrls);
};

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = !isEditing.value;
  if (isEditing.value) {
    // 进入编辑模式，复制数据
    Object.assign(formData, venueData.value);
    setupEditData();
  }
};

// 设置编辑数据
const setupEditData = () => {
  // 设置图片
  if (venueData.value.images) {
    try {
      const images = JSON.parse(venueData.value.images);
      if (Array.isArray(images)) {
        imageFiles.value = images.map(url => ({ url }));
      } else {
        imageFiles.value = [{ url: images }];
      }
    } catch (error) {
      console.error('解析图片失败:', error);
    }
  }
  
  // 设置设施
  if (venueData.value.facilities) {
    try {
      const facilities = JSON.parse(venueData.value.facilities);
      if (Array.isArray(facilities)) {
        facilitiesList.value = facilities;
      }
    } catch (error) {
      console.error('解析设施失败:', error);
    }
  }
};

// 监听设施变化
watch(facilitiesList, (newVal) => {
  formData.facilities = JSON.stringify(newVal);
}, { deep: true });

const handleCancel = () => {
  if (venueData.value.id) {
    isEditing.value = false;
    // 恢复原始数据
    Object.assign(formData, venueData.value);
    setupEditData();
  } else {
    goBack();
  }
};

const handleSubmit = () => {
  formRef.value.validate().then(async () => {
    try {
      uni.showLoading({ title: '保存中...' });
      
      // 设置门店ID
      if (storeId.value) {
        formData.store_id = storeId.value;
      }
      
      if (venueId.value) {
        await updateVenue(venueId.value, formData as Venue);
        uni.showToast({ title: '更新成功' });
        // 更新本地数据
        Object.assign(venueData.value, formData);
        isEditing.value = false;
      } else {
        const result = await createVenue(formData as Venue);
        uni.showToast({ title: '创建成功' });
        setTimeout(() => {
          uni.redirectTo({ 
            url: `/pages/venues/detail?id=${result.id}&storeId=${storeId.value}` 
          });
        }, 1500);
      }
    } catch (error: any) {
      uni.showToast({ title: error.message || '操作失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  }).catch((err: any) => {
    console.log('表单校验失败', err);
  });
};

const goBack = () => {
  uni.navigateBack();
};

// 快速预订
const handleQuickBook = () => {
  if (venueId.value && storeId.value) {
    uni.navigateTo({ 
      url: `/pages/bookings/create?venueId=${venueId.value}&storeId=${storeId.value}` 
    });
  }
};

// 显示状态弹窗
const showStatusModal = () => {
  statusPopup.value?.open();
};

// 关闭状态弹窗
const closeStatusModal = () => {
  statusPopup.value?.close();
};

// 切换场地状态
const changeVenueStatus = async (status: number) => {
  if (!venueId.value) return;
  
  try {
    await updateVenue(venueId.value, { status });
    uni.showToast({ title: '状态更新成功' });
    venueData.value.status = status;
    formData.status = status;
    closeStatusModal();
  } catch (error) {
    uni.showToast({ title: '状态更新失败', icon: 'none' });
  }
};

// 获取场地类型列表
const getVenueTypes = async () => {
  try {
    const res = await fetchVenueTypes();
    venueTypeOptions.value = res.map((type: VenueType) => ({ 
      value: type.name, 
      text: type.name 
    }));
  } catch (error) {
    console.error('获取场地类型失败:', error);
  }
};

onLoad(async (options: any) => {
  await getVenueTypes();
  
  if (options.storeId) {
    storeId.value = Number(options.storeId);
  }
  
  if (options.id) {
    venueId.value = Number(options.id);
    pageTitle.value = '场地详情';
    uni.setNavigationBarTitle({ title: pageTitle.value });
    
    try {
      const res = await fetchVenueDetail(venueId.value);
      venueData.value = res;
      Object.assign(formData, res);
      setupEditData();
    } catch (error) {
      uni.showToast({ title: '获取场地详情失败', icon: 'none' });
    }
  } else {
    isEditing.value = true;
    uni.setNavigationBarTitle({ title: pageTitle.value });
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.form-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.image-section {
  position: relative;
  height: 200px;
}

.venue-swiper {
  width: 100%;
  height: 100%;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
}

.back-btn, .edit-btn {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background-color: rgba(0,0,0,0.3);
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-section {
  margin: 10px;
}

.status-card {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 15px;
  box-shadow: var(--shadow);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-label {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.status-actions {
  display: flex;
  gap: 10px;
}

.status-btn, .book-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
}

.status-btn {
  background-color: #f5f5f5;
  color: #666;
}

.book-btn {
  background-color: var(--primary-color);
  color: #fff;
  
  &:disabled {
    background-color: #ccc;
    color: #999;
  }
}

.uni-card {
  margin: 10px !important;
}

.input-with-unit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.unit {
  font-size: 14px;
  color: var(--text-color-secondary);
  white-space: nowrap;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  display: flex;
  gap: 10px;
}

.edit-btn-footer {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: var(--primary-color);
  color: #fff;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.cancel-btn, .submit-btn {
  flex: 1;
  height: 44px;
  border-radius: var(--border-radius);
  font-size: 16px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.submit-btn {
  background-color: var(--primary-color);
  color: #fff;
}

.status-modal {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.status-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.status-option {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.status-desc {
  margin-left: 12px;
  font-size: 14px;
  color: var(--text-color-secondary);
}
</style>